package com.kreao.korean.controller;

import com.kreao.korean.dto.ApiResponse;
import com.kreao.korean.entity.DatabaseMigration;
import com.kreao.korean.infrastructure.service.DatabaseMigrationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 数据库迁移管理控制器
 * 提供迁移历史查询和手动执行功能
 */
@Slf4j
@RestController
@RequestMapping("/admin/migrations")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")  // 仅管理员可访问
public class MigrationController {

    private final DatabaseMigrationService migrationService;

    /**
     * 获取迁移历史1
     */
    @GetMapping("/history")
    public ResponseEntity<ApiResponse<List<DatabaseMigration>>> getMigrationHistory() {
        try {
            List<DatabaseMigration> history = migrationService.getMigrationHistory();
            return ResponseEntity.ok(ApiResponse.success("获取迁移历史成功", history));
        } catch (Exception e) {
            log.error("获取迁移历史失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取迁移历史失败: " + e.getMessage()));
        }
    }

    /**
     * 手动执行数据库迁移
     * 注意：这个接口应该谨慎使用，通常在开发或紧急情况下才需要手动触发
     */
    @PostMapping("/execute")
    public ResponseEntity<ApiResponse<String>> executeMigrations() {
        try {
            log.info("管理员手动触发数据库迁移");
            migrationService.migrate();
            return ResponseEntity.ok(ApiResponse.success("迁移执行成功", "数据库迁移执行完成"));
        } catch (Exception e) {
            log.error("手动执行迁移失败", e);
            return ResponseEntity.ok(ApiResponse.error("迁移执行失败: " + e.getMessage()));
        }
    }

    /**
     * 获取迁移状态信息
     */
    @GetMapping("/status")
    public ResponseEntity<ApiResponse<MigrationStatus>> getMigrationStatus() {
        try {
            List<DatabaseMigration> history = migrationService.getMigrationHistory();
            
            long totalMigrations = history.size();
            long successfulMigrations = history.stream()
                .filter(m -> m.getStatus() == DatabaseMigration.MigrationStatus.SUCCESS)
                .count();
            long failedMigrations = history.stream()
                .filter(m -> m.getStatus() == DatabaseMigration.MigrationStatus.FAILED)
                .count();
            
            DatabaseMigration latestMigration = history.stream()
                .filter(m -> m.getStatus() == DatabaseMigration.MigrationStatus.SUCCESS)
                .max((m1, m2) -> m1.getVersion().compareTo(m2.getVersion()))
                .orElse(null);
            
            MigrationStatus status = MigrationStatus.builder()
                .totalMigrations(totalMigrations)
                .successfulMigrations(successfulMigrations)
                .failedMigrations(failedMigrations)
                .latestVersion(latestMigration != null ? latestMigration.getVersion() : null)
                .latestMigrationTime(latestMigration != null ? latestMigration.getExecutedAt() : null)
                .build();
            
            return ResponseEntity.ok(ApiResponse.success("获取迁移状态成功", status));
        } catch (Exception e) {
            log.error("获取迁移状态失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取迁移状态失败: " + e.getMessage()));
        }
    }

    /**
     * 迁移状态信息
     */
    @lombok.Data
    @lombok.Builder
    public static class MigrationStatus {
        private Long totalMigrations;          // 总迁移数
        private Long successfulMigrations;     // 成功迁移数
        private Long failedMigrations;         // 失败迁移数
        private String latestVersion;          // 最新版本
        private java.time.LocalDateTime latestMigrationTime;  // 最新迁移时间
    }
} 